import base64
import hmac
import time
import json

# 生成token
header = {"alg": "HS256", "typ": "JWT"}
header_str = json.dumps(header)
header_bs = base64.b64encode(header_str.encode())
print(header_bs)  # b'eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9'

payload = {
    "exp": int(time.time()) + 5,
    "username": "zhaoliying",
}
payload_str = json.dumps(payload)
payload_bs = base64.b64encode(payload_str.encode())
print(payload_bs)  # b'eyJleHAiOiAxNjg3MTUyNjU5LCAidXNlcm5hbWUiOiAiemhhb2xpeWluZyJ9'

key = b"123456"
msg = header_bs + b"." + payload_bs
sign_str = hmac.new(key=key, msg=msg, digestmod="SHA256").hexdigest()
sign_bs = base64.b64encode(sign_str.encode())
print(sign_bs)  # b'MDRjYWE3Yjc2MjMzYzcxYjViYjYwODU3YjgzMGNmY2JkNjljZTY5MjViYTlhYTVhMDEwNmY1MWUwMDE4NDE0ZQ=='

token = msg + b"." + sign_bs
print(token)  # b'eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJleHAiOiAxNjg3MTUyODM1LCAidXNlcm5hbWUiOiAiemhhb2xpeWluZyJ9.MDRjYWE3Yjc2MjMzYzcxYjViYjYwODU3YjgzMGNmY2JkNjljZTY5MjViYTlhYTVhMDEwNmY1MWUwMDE4NDE0ZQ=='


# 校验token
#   合法性
x, y, z = token.split(b".")
sign_user = hmac.new(key=key, msg=x + b"." + y, digestmod="SHA256").hexdigest()
sign_user = base64.b64encode(sign_user.encode())
if sign_user != z:
    print("token不合法")

#   有效期
# time.sleep(6)
payload = base64.b64decode(y).decode()
payload = json.loads(payload)
exp = payload.get("exp")
now = time.time()


if now > exp:
    print("已过期,请重新登陆")

username = payload.get("username")
